package com.jingyanzi.finance.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.finance.dao.CashBillMapper;
import com.jingyanzi.finance.dao.CashSerialMapper;
import com.jingyanzi.finance.domain.CashBillDO;
import com.jingyanzi.finance.domain.CashCashierDO;
import com.jingyanzi.finance.domain.CashPayRecordDO;
import com.jingyanzi.finance.domain.CashPlaceDO;
import com.jingyanzi.finance.entity.CashBill;
import com.jingyanzi.finance.entity.CashBillExample;
import com.jingyanzi.finance.entity.CashBillExample.Criteria;
import com.jingyanzi.finance.entity.CashSerial;
import com.jingyanzi.finance.entity.CashSerialExample;
import com.jingyanzi.finance.query.CashBillQueryDO;
import com.jingyanzi.finance.query.CashCashierQueryDO;
import com.jingyanzi.finance.result.ResultDO;
import com.jingyanzi.finance.result.ResultSupport;
import com.jingyanzi.finance.service.IBillService;
import com.jingyanzi.finance.service.ICashierService;
import com.jingyanzi.finance.service.IPayRecordService;
import com.jingyanzi.finance.service.IPlaceService;
import com.jingyanzi.finance.util.BeanUtilsExtends;
import com.jingyanzi.finance.util.DateUtil;
import com.jingyanzi.finance.util.ExportUtil;
import com.jingyanzi.member.domain.AccountFinanceDO;
import com.jingyanzi.member.domain.AccountPayDO;
import com.jingyanzi.member.domain.ApiDO;
import com.jingyanzi.member.domain.CustomerDO;
import com.jingyanzi.member.domain.IntegralDO;
import com.jingyanzi.member.factory.MemberFactory;
import com.jingyanzi.member.service.IAccountService;
import com.jingyanzi.member.service.ICustomerService;
import com.jingyanzi.member.service.IIntegralLogService;
import com.jingyanzi.order.domain.OrderCashierDO;
import com.jingyanzi.order.factory.OrderFactory;
import com.jingyanzi.order.service.PackageOrderService;
import com.jingyanzi.privilege.domain.EmployeeDO;
import com.jingyanzi.privilege.factory.PrivilegeFactory;
import com.jingyanzi.privilege.service.IEmployeeService;
import com.jingyanzi.resallocation.domain.StoreDO;
import com.jingyanzi.resallocation.factory.ResFactory;
import com.jingyanzi.resallocation.service.IStoreService;
import com.jingyanzi.sys.domain.DictionariesDO;
import com.jingyanzi.sys.domain.service.ISettingService;
import com.jingyanzi.sys.factory.SysFactory;

@Service("billService")
public class BillServiceImpl extends BaseServiceImpl implements IBillService {

	/**
	 * 记录日志变量
	 */
	private static Logger logger = Logger.getLogger(BillServiceImpl.class);

	@Autowired
	private CashBillMapper cashBillMapper;

	@Autowired
	private IPayRecordService payRecordService;

	@Autowired
	private IPlaceService placeService;

	@Autowired
	private CashSerialMapper cashSerialMapper;

	@Autowired
	private ICashierService cashierService;

	private ICustomerService getCustomerService() {
		return MemberFactory.getCustomerService();
	}

	private IStoreService getStoreService() {
		return ResFactory.getStoreService();
	}

	private IEmployeeService getEmployeeService() {
		return PrivilegeFactory.getEmployeeService();
	}

	private ISettingService getSettingService() {
		return SysFactory.getISettingService();
	}

	private IAccountService getAccountService() {
		return MemberFactory.getAccountService();
	}

	private PackageOrderService getPackageOrderService() {
		return OrderFactory.getPackageOrderService();
	}

	private IIntegralLogService getIntegralLogService() {
		return MemberFactory.getIntegralLogService();
	}

	private IAccountService getIAccountService() {

		return MemberFactory.getAccountService();
	}

	public ResultDO add(CashBillDO domain) {

		CashBill entity = new CashBill();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess())
			return result;

		entity.setCreatetime(Calendar.getInstance().getTime());
		entity.setModifitime(entity.getCreatetime());
		entity.setModifi(entity.getAuthor());
		entity.setStatus(0);
		entity.setIsDelete(1);
		// entity.setVoucherNO(getVoucherNO());

		if (domain.getBillType() != 4) {
			// 获得会员信息
			com.jingyanzi.member.domain.result.ResultDO res1 = getCustomerService().get(entity.getCustomId());

			if (!res1.isSuccess()) {

				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
				result.setSuccess(false);
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
				return result;
			}

			CustomerDO customerDO = (CustomerDO) res1.getModel(ResultDO.FIRST_MODEL_KEY);
			if (customerDO.getFirstFamilyMember() == null) {
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
				result.setSuccess(false);
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
				return result;
			}

			entity.setCustomName(customerDO.getFirstFamilyMember().getName());
			entity.setCustomTel(customerDO.getFirstFamilyMember().getTelephone());
		}
		if (domain.getBillType() != 5) {
			// 获取门店信息
			com.jingyanzi.resallocation.result.ResultDO res2 = getStoreService().get(domain.getStoreId());

			if (!res2.isSuccess()) {

				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
				result.setSuccess(false);
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
				return result;
			}

			StoreDO storeDO = (StoreDO) res2.getModel(ResultSupport.FIRST_MODEL_KEY);
			if (storeDO == null) {
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
				result.setSuccess(false);
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
				return result;
			}
			entity.setStoreName(storeDO.getName());
		}

		// 获取销售员工信息
		if (null != domain.getSaleId() && domain.getSaleId() > 0) {
			EmployeeDO employeeDO = getEmployee(domain.getSaleId());
			if (employeeDO == null) {
				System.out.println("employeeDO");
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取员工信息失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取员工信息失败");
				return result;
			}
			entity.setSaleName(employeeDO.getRealName());
		}

		if (entity.getBillType() == 4) {
			entity.setBillNO(getBusinessNO());
		}

		entity.setBillTypeName(PAY_CASH_NAMES.get(entity.getBillType()));
		entity.setArrearsAmount(entity.getAmount());
		entity.setReceivedAmount(new BigDecimal(0.0));
		int r = -1;

		try {
			r = cashBillMapper.insert(entity);
		} catch (Exception e) {
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + e.getMessage());
		}

		if (r < 0) {
			result.setSuccess(false);
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	public ResultDO pay(CashBillDO domain) {

		CashBill entity = null;

		ResultSupport result = new ResultSupport();

		// 读取账单信息
		try {
			entity = cashBillMapper.selectByPrimaryKey(domain.getId());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}

		if (entity == null) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}

		CashPayRecordDO payRecordDO = new CashPayRecordDO();

		String tradeNO = getTradeNO(domain.getCashierId());

		if (tradeNO == null) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获得交易流水号失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获得交易流水号失败");
			return result;
		}

		payRecordDO.setTradeNO(tradeNO);
		String businessNO = entity.getBillNO();
		if (entity.getBillType() == 4) {
			businessNO = "OT" + entity.getBillNO();
		}
		payRecordDO.setBusinessNO(businessNO);
		payRecordDO.setMappingId(entity.getId());
		payRecordDO.setCashierId(domain.getCashierId());
		EmployeeDO employeeDO = getEmployee(domain.getCashierId());
		if (employeeDO == null) {

			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取员工信息失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取员工信息失败");
			return result;
		}
		payRecordDO.setBillType(entity.getBillType());
		payRecordDO.setCashierName(employeeDO.getRealName());
		payRecordDO.setCustomId(entity.getCustomId());
		payRecordDO.setCustomName(entity.getCustomName());
		payRecordDO.setCustomTel(entity.getCustomTel());
		payRecordDO.setVoucherNO(domain.getVoucherNO());
		payRecordDO.setAmount(domain.getReceivedAmount());
		payRecordDO.setPayMethodId(domain.getPayMethodId());
		payRecordDO.setPayMethod(PAY_METHOD_NAMES.get(domain.getPayMethodId()));
		payRecordDO.setCashType(domain.getPayTypeId());
		if (entity.getBillType() == 1) {
			payRecordDO.setOrderId(entity.getOrderId());
		} else {
			payRecordDO.setOrderNO("");
		}
		payRecordDO.setOrderNO(entity.getBillNO());
		payRecordDO.setRemarks(domain.getRemarks());
		// 要从字典查收款类型
		// 获取字典信息
		com.jingyanzi.sys.domain.result.ResultDO res5 = getSettingService().getDictionariesById(domain.getPayTypeId());
		if (!res5.isSuccess()) {

			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取字典信息失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取字典信息失败");
			return result;
		}

		DictionariesDO dic = (DictionariesDO) res5.getModel(ResultSupport.FIRST_MODEL_KEY);

		payRecordDO.setCashTypeName(dic.getDataItem());

		payRecordDO.setInvoiceStatus(domain.getInvoiceStatus());
		payRecordDO.setAuthor(domain.getAuthor());
		payRecordDO.setModifi(domain.getAuthor());
		// 通过收银员ID查询绑定的收银地点
		ResultDO res3 = placeService.getPlaceByEmployeeId(domain.getCashierId());
		if (!res3.isSuccess()) {

			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取收银地点失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取收银地点失败");
			return result;
		}

		CashPlaceDO placeDO = (CashPlaceDO) res3.getModel(ResultSupport.FIRST_MODEL_KEY);
		payRecordDO.setPlaceId(placeDO.getId());
		payRecordDO.setPlaceName(placeDO.getPlaceName());

		ResultDO res = payRecordService.add(payRecordDO);

		if (!res.isSuccess()) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 添加收银记录失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 添加收银记录失败");
			return result;
		}

		Map<String, Object> items = new HashMap<String, Object>();
		items.put(ExportUtil.pdfBillKey[0], domain.getVoucherNO());
		items.put(ExportUtil.pdfBillKey[1], businessNO);
		items.put(ExportUtil.pdfBillKey[2], entity.getCustomName());
		items.put(ExportUtil.pdfBillKey[3], entity.getCustomTel());
		items.put(ExportUtil.pdfBillKey[4], entity.getStoreName());
		items.put(ExportUtil.pdfBillKey[5], entity.getSaleName());
		items.put(ExportUtil.pdfBillKey[6], entity.getBillNO());
		items.put(ExportUtil.pdfBillKey[7], PAY_CASH_NAMES.get(entity.getBillType()));
		items.put(ExportUtil.pdfBillKey[8], entity.getAmount().toString());
		items.put(ExportUtil.pdfBillKey[9], (new BigDecimal(domain.getReceivedAmount().doubleValue())).toString());
		items.put(ExportUtil.pdfBillKey[10], payRecordDO.getCashierName());
		items.put(ExportUtil.pdfBillKey[11], payRecordDO.getPlaceName());
		items.put(ExportUtil.pdfBillKey[12], DateUtil.format(System.currentTimeMillis(), DateUtil.FMT_YMD_HMS));

		ExportUtil exprotUtil = ExportUtil.exportFactory(1);
		// 生成电子票据
		if (!exprotUtil.billWriter(items)) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 生成票据失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 生成票据失败");
			return result;
		}

		if (domain.getIsSms() == 1) {
			// 发送短信调用短信接口
		}

		if (domain.getIsElectronic() == 1) {
			// 调用微信接口发送电子账单
		}

		int r = -1;

		BigDecimal arrearsAmount = entity.getArrearsAmount().subtract(domain.getReceivedAmount());
		entity.setArrearsAmount(arrearsAmount);
		entity.setReceivedAmount(entity.getReceivedAmount().add(domain.getReceivedAmount()));
		if (arrearsAmount.doubleValue() < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "负数");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "负数");
			return result;
		}

		if (arrearsAmount.intValue() == 0) {
			entity.setStatus(1);
		} else {
			entity.setStatus(0);
		}

		if (entity.getBillType() == 3) {
			AccountFinanceDO accountFinanceDO = new AccountFinanceDO();
			accountFinanceDO.setAccountId(entity.getCustomId());
			accountFinanceDO.setTradeNo(entity.getBillNO());
			accountFinanceDO.setCashierId(domain.getCashierId());
			accountFinanceDO.setPayMode(domain.getPayMethodId());
			accountFinanceDO.setTradeType(entity.getBillType());
			accountFinanceDO.setTradeAmount(domain.getReceivedAmount());
			accountFinanceDO.setGiftAmount(new BigDecimal(0.00));
			accountFinanceDO.setTotleAmount(new BigDecimal(0.00));
			com.jingyanzi.member.domain.result.ResultDO res9 = getAccountService().addFinanceRecord(accountFinanceDO);
			if (!res9.isSuccess()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "用户充值失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "用户充值失败");
				return result;
			}
			logger.info("客户：" + entity.getCustomName() + "现金账户充值:" + domain.getReceivedAmount() + "元");
		}

		if (entity.getBillType() == 1 || entity.getBillType() == 2) {
			OrderCashierDO orderCashierDO = new OrderCashierDO();
			orderCashierDO.setOrderId(entity.getOrderId());
			orderCashierDO.setOrderDetailId(entity.getSalesLeadId());
			orderCashierDO.setPrice(domain.getReceivedAmount());
			com.jingyanzi.order.domain.result.ResultDO resOrder = getPackageOrderService().updateOrder(orderCashierDO);
			if (!resOrder.isSuccess()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "订单同步失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "订单同步失败");
				return result;
			}
			logger.info("客户：" + entity.getCustomName() + "订单支付:" + domain.getReceivedAmount() + "元");
			AccountPayDO accountPayDO = new AccountPayDO();
			accountPayDO.setAccountId(entity.getCustomId());
			accountPayDO.setTradeNo(getBusinessNO());
			accountPayDO.setOrderNo(entity.getBillNO());
			accountPayDO.setItemDesp(PAY_CASH_NAMES.get(entity.getBillType()));
			accountPayDO.setConsumeAmount(domain.getAmount());
			accountPayDO.setDiscountAmount(new BigDecimal(0.00));
			accountPayDO.setSettleAmount(domain.getReceivedAmount());
			accountPayDO.setStoreId(entity.getStoreId());
			accountPayDO.setSalesId(entity.getSaleId());
			accountPayDO.setCashierId(domain.getCashierId());
			accountPayDO.setTradeType(entity.getBillType());
			accountPayDO.setPayMode(domain.getPayMethodId());
			accountPayDO.setTradingDate(entity.getCreatetime());

			getAccountService().addPay(accountPayDO);
		}

		if (entity.getBillType() == 5) {
			AccountPayDO accountPayDO = new AccountPayDO();
			accountPayDO.setAccountId(entity.getCustomId());
			accountPayDO.setTradeNo(getBusinessNO());
			accountPayDO.setOrderNo(entity.getBillNO());
			accountPayDO.setItemDesp(PAY_CASH_NAMES.get(entity.getBillType()));
			accountPayDO.setConsumeAmount(domain.getAmount());
			accountPayDO.setDiscountAmount(new BigDecimal(0.00));
			accountPayDO.setSettleAmount(domain.getReceivedAmount());
			accountPayDO.setStoreId(entity.getStoreId());
			accountPayDO.setSalesId(entity.getSaleId());
			accountPayDO.setCashierId(domain.getCashierId());
			accountPayDO.setTradeType(entity.getBillType());
			accountPayDO.setPayMode(domain.getPayMethodId());
			accountPayDO.setTradingDate(entity.getCreatetime());

			com.jingyanzi.member.domain.result.ResultDO res4 = getAccountService().addPay(accountPayDO);
			if (!res4.isSuccess()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "购买会员失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "购买会员失败");
				return result;
			}
			logger.info("客户：" + entity.getCustomName() + "购买会员支付:" + domain.getReceivedAmount() + "元");
		}

		// 更新账单状态
		try {
			r = cashBillMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "更新账单失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "更新账单失败");
			return result;
		}

		if (r < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "更新账单失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "更新账单失败");
			return result;
		}

		if (domain.getIsPrint() == 1) {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
			Properties p = new Properties();
			try {
				p.load(inputStream);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			String billUrl = p.getProperty("doc.download.path");
			result.setModel(ResultSupport.FIRST_MODEL_KEY, billUrl + payRecordDO.getVoucherNO() + ".pdf");
		}

		if (domain.getPayMethodId() == 4 && entity.getCustomId() != null) {
			// 调用余额接口
			Integer cid = entity.getCustomId();// 用户id
			BigDecimal bg = domain.getReceivedAmount();// 实际支付金额

			com.jingyanzi.member.domain.result.ResultDO info = getCustomerService().getInfoForPayment(cid);

			ApiDO api = null;

			if (info.isSuccess()) {
				api = (ApiDO) info
						.getModel(com.jingyanzi.member.domain.result.ResultDO.FIRST_MODEL_KEY);

			} else {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "账户查询失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "账户查询失败");
				return result;
			}
			System.out.println(api);
			BigDecimal balance = api.getBalance();// 账户余额
			Integer isMember = api.getIsMember();// 是否会员 0不是会员 1是会员
			if (bg.doubleValue() > balance.doubleValue()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "账户余额不足");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "账户余额不足");
				return result;
			}
			// 为会员时添加积分
			if (isMember == 1) {
				// 调用积分接口更新用户 积分
				IntegralDO integralDO = new IntegralDO();
				integralDO.setMemberId(entity.getCustomId());
				integralDO.setIntegral(domain.getReceivedAmount().intValue());
				integralDO.setOpType(1); // TODO:新增积分
				if (entity.getBillType() == 3) {
					integralDO.setOpInfo("充值积分"); // 充值积分
				} else {
					integralDO.setOpInfo("消费积分"); // 订单、加选等其他消费积分
				}
				integralDO.setAuthor(domain.getAuthor());
				integralDO.setTradeNo(businessNO); // businessNO ? tradeNo?
				logger.info("客户：" + entity.getCustomName() + "通过支付获得积分:" + domain.getReceivedAmount().intValue());
				com.jingyanzi.member.domain.result.ResultDO res6 = getIntegralLogService().addLog(integralDO);
				if (!res6.isSuccess()) {
					result.setSuccess(false);
					result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
					result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "积分修改错误");
					logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "积分修改错误");
					return result;
				}
			}

			// 改变账户余额
			AccountFinanceDO accountFinanceDO = new AccountFinanceDO();

			accountFinanceDO.setAccountId(entity.getCustomId());
			accountFinanceDO.setTradeNo(tradeNO);
			accountFinanceDO.setTradeType(entity.getBillType());
			accountFinanceDO.setPayMode(domain.getPayMethodId());
			accountFinanceDO.setTradeAmount(bg);
			accountFinanceDO.setGiftAmount(new BigDecimal(0));
			accountFinanceDO.setTotleAmount(bg);
			accountFinanceDO.setCashierId(domain.getCashierId());
			
			com.jingyanzi.member.domain.result.ResultDO addFinanceRecord = getIAccountService()
					.addFinanceRecord(accountFinanceDO);
			if (!addFinanceRecord.isSuccess()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "修改账户失败");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "修改账户失败");
				return result;
			}

		}

		return result;
	}

	public Properties getProperties() {
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
		} catch (IOException e1) {
			return null;
		}
		return properties;
	}

	public ResultDO modifi(CashBillDO domain) {

		CashBill entity = new CashBill();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess())
			return result;

		int r = -1;

		try {
			r = cashBillMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (r < 1) {
			result.setSuccess(false);
		}

		return result;
	}

	public ResultDO remove(Integer id) {

		CashBill entity = new CashBill();

		ResultSupport result = new ResultSupport();

		int r = -1;
		entity.setId(id);
		entity.setIsDelete(-1);
		try {
			r = cashBillMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (r < 1) {
			result.setSuccess(false);
		}
		return result;
	}

	public ResultDO removeForOrderId(Integer orderId) {

		ResultSupport result = new ResultSupport();

		CashBillExample example = new CashBillExample();

		Criteria createCriteria = example.createCriteria();

		createCriteria.andOrderIdEqualTo(orderId).andIsDeleteEqualTo(1);

		int r = -1;

		try {
			r = cashBillMapper.deleteByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "删除订单对于应的账单失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + e.getMessage());
			return result;
		}

		if (r < 0) {
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "删除订单对于应的账单失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "删除订单对于应的账单失败");
		}
		return result;
	}

	public ResultDO get(Integer id, Integer cashierId) {

		CashBill entity = new CashBill();

		ResultSupport result = new ResultSupport();

		try {
			entity = cashBillMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (entity == null) {
			result.setSuccess(false);
		}

		CashBillDO cashBillDO = getCashBillDO(entity);

		if (cashierId == null) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "没有收银员");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "没有收银员");
			return result;
		}

		if (entity.getCustomId() != null) {
			com.jingyanzi.member.domain.result.ResultDO res6 = getCustomerService().get(entity.getCustomId());

			if (!res6.isSuccess()) {
				result.setSuccess(false);
				result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "该用户不存在");
				logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "该用户不存在");
				return result;
			}

			CustomerDO customerDO = (CustomerDO) res6.getModel(ResultSupport.FIRST_MODEL_KEY);

			cashBillDO.setIsMember(customerDO.getIsMember());
		} else {
			cashBillDO.setIsMember(0);
		}
		CashCashierQueryDO query = new CashCashierQueryDO();
		query.setEmployeeId(cashierId);
		ResultDO res = cashierService.query(query);

		if (!res.isSuccess()) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "收银人员失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "收银人员失败");
			return result;
		}

		List<CashCashierDO> listDO = (List<CashCashierDO>) res.getModel(ResultSupport.FIRST_MODEL_KEY);

		if (listDO.size() == 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "不是收银员");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "不是收银员");
			return result;
		}

		/*
		 * CashCashierDO cashierDO = listDO.get(0); if(cashierDO != null) {
		 * cashBillDO.setCashierId(cashierId);
		 * cashBillDO.setCashierName(cashierDO.getName()); } else {
		 * cashBillDO.setCashierId(0); cashBillDO.setCashierName(""); }
		 * //通过收银员ID查询绑定的收银地点 ResultDO res3 =
		 * placeService.getPlaceByEmployeeId(cashierId);
		 * 
		 * if(!res3.isSuccess()) { result.setSuccess(false);
		 * result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
		 * result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG +
		 * "pay 获取收银地点失败"); logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG +
		 * "pay 获取收银地点失败"); return result; }
		 * 
		 * CashPlaceDO placeDO = (CashPlaceDO)
		 * res3.getModel(ResultSupport.FIRST_MODEL_KEY); if(placeDO != null) {
		 * cashBillDO.setPlaceId(placeDO.getId());
		 * cashBillDO.setPlaceName(placeDO.getPlaceName()); } else {
		 * cashBillDO.setPlaceId(0); cashBillDO.setPlaceName(""); }
		 */
		cashBillDO.setBusinessNO(entity.getBillNO());
		cashBillDO.setOrderNO(entity.getOrderNO());

		cashBillDO.setVoucherNO(getVoucherNO());
		cashBillDO.setCreatetime(System.currentTimeMillis() + "");

		result.setModel(ResultSupport.FIRST_MODEL_KEY, cashBillDO);
		return result;
	}

	public ResultDO query(CashBillQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<CashBill> list = null;

		CashBillExample example = new CashBillExample();

		Criteria createCriteria = example.createCriteria();

		createCriteria.andIsDeleteEqualTo(1);

		if (query.getStatus() != null) {
			if (query.getStatus() != 2) {
				createCriteria.andStatusEqualTo(query.getStatus());
			}
		}

		if (query.getNameOrTel() != null) {
			if (isChinaPhoneLegal(query.getNameOrTel())) {
				createCriteria.andCustomTelLike("%" + query.getNameOrTel() + "%");
			} else {
				createCriteria.andCustomNameLike("%" + query.getNameOrTel() + "%");
			}
		}

		if (StringUtils.isNotEmpty(query.getStartTimeStamp()) && StringUtils.isNotEmpty(query.getEndTimeStamp())) {

			Date startTime = new Date(Long.parseLong(query.getStartTimeStamp()));
			Date endTime = new Date((Long.parseLong(query.getEndTimeStamp()) + (24 * 60 * 60 * 1000)));

			createCriteria.andCreatetimeBetween(startTime, endTime);
		}

		if (isNumberNotEmpty(query.getBillType())) {
			createCriteria.andBillTypeEqualTo(query.getBillType());
		}

		if (isNumberNotEmpty(query.getCustomId())) {
			createCriteria.andCustomIdEqualTo(query.getCustomId());
		}

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = cashBillMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		List<CashBillDO> doList = new ArrayList<CashBillDO>();

		try {
			list = cashBillMapper.selectByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "查询失败");
			logger.error(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + e.getMessage());
			return result;
		}

		doList = getCashBillDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, doList);

		return result;
	}

	public CashBillDO getCashBillDO(CashBill entity) {
		if (entity == null)
			return null;
		CashBillDO dst = new CashBillDO();
		return BeanUtilsExtends.copyProperties(dst, entity) ? dst : null;
	}

	public List<CashBillDO> getCashBillDOList(List<CashBill> list) {
		List<CashBillDO> result = new ArrayList<CashBillDO>();
		if (list != null && !list.isEmpty()) {
			for (CashBill org : list) {
				CashBillDO org1 = getCashBillDO(org);
				if (org1 != null) {
					org1.setBusinessNO(org.getBillNO());
					org1.setOrderNO(org.getOrderNO());
					org1.setCreatetime(org.getCreatetime().getTime() + "");
					result.add(org1);
				}
			}
		}
		return result;
	}

	private String getVoucherNO() {
		Random rand = new Random();// 生成随机数
		String voucherNO = "";
		for (int a = 0; a < 8; a++) {
			voucherNO += rand.nextInt(10);// 生成8位数字
		}
		return voucherNO;
	}

	private String getTradeNO(int emid) {
		SimpleDateFormat df = new SimpleDateFormat("YYYYMMdd");
		String dateStr = df.format(new Date());
		CashSerialExample example = new CashSerialExample();
		List<CashSerial> list = null;
		example.createCriteria().andCreatetimeEqualTo(dateStr);
		try {
			list = cashSerialMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		if (list.size() > 1) {
			return null;
		}

		int r = -1;
		int serialNumber = 1;

		if (list.size() == 0) {
			// 没有流水号时创建今天的流水号
			CashSerial cashSerial = new CashSerial();
			cashSerial.setCreatetime(dateStr);
			cashSerial.setSerialNumber(serialNumber);
			try {
				r = cashSerialMapper.insertSelective(cashSerial);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			// 今天的流水号存在的时候更新
			CashSerial cashSerial = list.get(0);
			serialNumber = cashSerial.getSerialNumber() + 1;
			cashSerial.setSerialNumber(serialNumber);
			try {
				r = cashSerialMapper.updateByPrimaryKeySelective(cashSerial);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		if (r < 0) {
			return null;
		}

		EmployeeDO employeeDO = getEmployee(emid);

		if (employeeDO == null) {
			System.out.println(" Tradno employeeDO IS NULL");
			return null;
		}

		return dateStr + employeeDO.getWorkNo() + serialNumber;
	}

	private String getBusinessNO() {
		SimpleDateFormat df = new SimpleDateFormat("YYYYMMdd");
		String dateStr = df.format(new Date());
		dateStr += Calendar.getInstance().get(Calendar.SECOND);
		int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < 4; i++)
			result = result * 10 + array[i];

		return dateStr + result;
	}

	public EmployeeDO getEmployee(int id) {
		// 获取销售员工信息
		com.jingyanzi.privilege.domain.result.ResultDO res = getEmployeeService().getEmployee(id);

		if (!res.isSuccess()) {
			return null;
		}
		EmployeeDO employeeDO = (EmployeeDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
		return employeeDO;
	}

}
